package com.atqar.rwlock;


import java.util.concurrent.locks.ReentrantReadWriteLock;

class mythrod{
    ReentrantReadWriteLock rwlock=new ReentrantReadWriteLock();


    public void write(){
        rwlock.writeLock().lock();
        System.out.println("抢到写锁");
        rwlock.readLock().lock();
        System.out.println("抢到写锁");


        rwlock.writeLock().unlock();
        System.out.println("释放写锁");

        rwlock.readLock().unlock();
        System.out.println("释放写锁");
    }


    //错误的锁降级示例，因为在释放写锁和获取读锁之间能够有其他的写线程插入，从而影响数据的一致性
    public void writeerror(){
        rwlock.writeLock().lock();
        System.out.println("获取到写锁");

        System.out.println("释放写锁");
        rwlock.writeLock().unlock();

        //可能插入其他写线程

        System.out.println("获取到读锁");
        rwlock.readLock().lock();

        rwlock.readLock().unlock();
        System.out.println("释放读锁");
    }

}

public class ReadWriteDownLoceDemo {

    public static void main(String[] args) {
        mythrod mythrod = new mythrod();
        new Thread(()->{
            mythrod.write();
        }).start();

    }

}
